package com.atwork.wuhua.mvp.presenter;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.style.ImageSpan;

import com.atwork.wuhua.base.BasePresenter;
import com.atwork.wuhua.base.BaseReq;
import com.atwork.wuhua.bean.FileLoadBean;
import com.atwork.wuhua.bean.TypeSelectRegionBean;
import com.atwork.wuhua.mvp.Callback;
import com.atwork.wuhua.mvp.DataModel;
import com.atwork.wuhua.mvp.Token;
import com.atwork.wuhua.mvp.view.IPostActivity;
import com.atwork.wuhua.utils.HttpUtil.HttpConfig;
import com.atwork.wuhua.utils.LogUtils;
import com.atwork.wuhua.utils.StringUtil;
import com.atwork.wuhua.utils.TimeUtil;
import com.atwork.wuhua.utils.UserUtil;
import com.atwork.wuhua.utils.Util;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PostPresenter extends BasePresenter<IPostActivity> {

    public void getRegion() {
        BaseReq req = new BaseReq();
        req.setKey("type", "area");
        req.setKey("parent", "3502");
        DataModel.request(Token.API_LOCATION)
                .params(req)
                .execute(new Callback<TypeSelectRegionBean>() {

                    public void onSuccess(String msg, TypeSelectRegionBean data) {
                        getView().getRegionResult(data);

                    }

                    @Override
                    public void onFailure(String msg) {
                    }

                    @Override
                    public void onError() {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private int curIndex = 0;
    private List<String> localList = new ArrayList<>(); //本地的集合
    private List<String> stringList = new ArrayList<>(); //上传的集合

    public void postImage(List<String> list) {
        localList = list;
        LogUtils.e("localList==>" + localList.size());
        LogUtils.e("stringList.size==>" + stringList.size());
        LogUtils.e("curIndex==>" + curIndex);
        if (list.get(curIndex).length() > 8) {
            if ("/storage".equals(StringUtil.getIndexInSymbol(list.get(curIndex), 8))) {
                uploadImg(localList.get(curIndex));
            } else {
                //文字
                stringList.add(list.get(curIndex));
                if (localList.size() > stringList.size()) {
                    curIndex++;
                    postImage(localList);
                } else {
                    postIssuance(stringList);
                    LogUtils.e("上传成功222");
                    for (int i = 0; i < stringList.size(); i++) {
                        LogUtils.e("222==>" + stringList.get(i));
                    }
                }
            }
        } else {
            if (localList.size() > stringList.size()) {
                curIndex++;
                postImage(localList);
            } else {
                postIssuance(stringList);
                LogUtils.e("上传成功111");
                for (int i = 0; i < stringList.size(); i++) {
                    LogUtils.e("111==>" + stringList.get(i));
                }
            }
        }

    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    showToast("图片上传失败");
                    break;
                case 1:
//                    showToast("图片上传成功");
                    LogUtils.e("图片返回==》" + msg.obj);
                    Gson gson = new Gson();
                    FileLoadBean entity = gson.fromJson((String) msg.obj, FileLoadBean.class);
                    if (entity.getErrno().equals("000")) {
                        stringList.add(entity.getResult().getFile());
                        if (localList.size() > stringList.size()) {
                            curIndex++;
                            postImage(localList);
                        } else {
                            postIssuance(stringList);
                            LogUtils.e("上传成功333");
                            for (int i = 0; i < stringList.size(); i++) {
                                LogUtils.e("333==>" + stringList.get(i));
                            }
                        }

//                        getView().upLoadImgResult(HttpConfig.IMG_URL + entity.getResult().getFile());
                    } else {
                        showToast("图片上传失败");
                    }

                    break;
            }

            super.handleMessage(msg);

        }
    };


    int pageSize = 100;

    public void postIssuance(List<String> list) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                sb.append(list.get(i));
            } else {
                sb.append("==" + list.get(i));
            }
        }
        if (sb.toString().length() > pageSize) {
            List<String> list1 = StringUtil.getStrList(sb.toString(), pageSize);
            LogUtils.e("size==>" + list1.size());
            for (int i = 0; i < list1.size(); i++) {
                BaseReq req = new BaseReq();
                req.setKey("name", list1.get(i));
                LogUtils.e("1111==>" + req.getString());
            }
        } else {
            BaseReq req = new BaseReq();
            req.setKey("name", sb.toString());
        }


        
    }


    public void uploadImg(String filePath) {
        OkHttpClient client = new OkHttpClient();
        // form 表单形式上传
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        File file = new File(filePath);
        // MediaType.parse() 里面是上传的文件类型。
        RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
        // 参数分别为， 请求key ，文件名称 ， RequestBody
        BaseReq req = new BaseReq();
        req.setKey("type", "posts");
        String filename = "zl" + TimeUtil.getCurrentTimeMillis() + ".png";
        requestBody.addFormDataPart("file", filename, body).addFormDataPart("secret", req.getSecret());

        Request request = new Request.Builder().url(HttpConfig.BASE_URL + "common/upload").post(requestBody.build()).build();
        // readTimeout("请求超时时间" , 时间单位);
        client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = 0;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Message message = new Message();
                message.what = 1;
                message.obj = string;
                handler.sendMessage(message);
            }


        });

    }


}
